<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/29/029
 * Time: 11:08
 */

namespace app\api\service;

use app\api\model\MemberBill;
use app\api\model\OrderBuy as OrderBuyModel;
use app\api\model\Order as OrderModel;
use app\api\service\NoteCode as NoteCodeService;
use app\api\model\Member as MemberModel;
use app\lib\exception\OrderException;
use think\facade\Request;
use app\api\model\Config as ConfigModel;
use app\api\service\Express as ExpressService;
use app\api\model\Express as ExpressModel;

class Order {

    /**
     * 订单号
     * @param $prefix
     * @return string
     */
    public static function makeOrderNo($prefix)
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn =
            $yCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $prefix . $orderSn;
    }

    /**
     * 发送售后短信，通知后台管理人员
     * @param $aftermarket_sn
     */
    public static function sendAfterSaleNote($aftermarket_sn) {
        // 短信通知
        $part_order_number = ConfigModel::get(['name' => 'order_inform_number']);
        $manage_mobile = $part_order_number['value'];
        $param = [
            'mobile' => $manage_mobile,
            'order_sn' => $aftermarket_sn,
            'type' => 3,
        ];
        NoteCode::send_code($param);
    }

    /**
     * 用户确认发货，发送售后单物流短信，通知后台管理人员
     * @param $aftermarket_sn
     */
    public static function sendAfterSaleLogisticsNote($aftermarket_sn) {
        // 短信通知
        $part_order_number = ConfigModel::get(['name' => 'order_inform_number']);
        $manage_mobile = $part_order_number['value'];
        // 短信通知
        $param = [
            'mobile' => $manage_mobile,
            'order_sn' => $aftermarket_sn,
            'type' => 5,
        ];
        NoteCode::send_code($param);
    }

    /**
     * 获取售后状态信息
     * @param $status
     * @return mixed
     */
    public static function get_order_after_sale_status($status) {
        $status_array = ['', '已申请', '已受理', '已支付', '用户寄回', '平台已收货', '平台已发出', '完成', '取消售后'];
        return $status_array[$status];
    }

    /**
     * 处理售后单详情需要显示的字段
     * @param $order_after_sale  // 售后详情对象
     * @return mixed
     */
    public static function orderAfterSaleVisible($order_after_sale) {
        $order_after_sale->visible(['id', 'member_express_sn', 'terrace_express_sn', 'aftermarket_sn', 'msg', 'create_time', 'status', 'price', 'order_buy', 'images'])
            ->order_buy->visible(['order_sn', 'order_buy_product'])
            ->order_buy_product->visible(['name', 'thumb', 'price', 'num']);
        return $order_after_sale;
    }

    /**
     * 首次下单推送微信模板消息提醒用户可代理商城
     * @param $uid
     * @param $member
     * @param $order_data
     * @param string $type
     */
    public static function checkMemberOrderNum($uid, $member, $order_data, $type = '定制') {
        $order = OrderModel::get(['member_id' => $uid]);
        $order_buy = OrderBuyModel::get(['member_id' => $uid]);
        if (!$order && !$order_buy) {
            if ($member && $member['openid']) {
                $param = [
                    'touser' => $member['openid'],
                    'template_id' => 'utZrSszP9y25svQG59t20Hz9QCvNNZUVEccxg_9TxUg',
                    'url' => '',
                    'data' => [
                        'first' => [ 'value' => '尊敬的用户您好', 'color' => '#173177'],
                        'keyword1' => [ 'value' => $order_data['order_sn'], 'color' => '#173177'],
                        'keyword2' => [ 'value' => $type, 'color' => '#173177'],
                        'keyword3' => [ 'value' => '￥' . $order_data['price'], 'color' => '#173177'],
                        'keyword4' => [ 'value' => date('Y-m-d H:i:s'), 'color' => '#173177'],
                        'remark' => [ 'value' => "感谢您对衣依不舍的信任和支持，现您已成功代理衣依定制商城，现在分享即可获得15%的分享提成，赶快行动吧! \n 服务热线：13348678093 宋经理", 'color' => '#173177'],
                    ]
                ];
                send_wechat_tmplmsg(json_encode($param));
            }
        }
    }

    /**
     * 订单创建成功  推送消息
     * @param $order_data
     * @param string $type
     */
    public static function sendCreateOrderMsg($order_data, $type = '定制') {

        $part_order_number = ConfigModel::get(['name' => 'part_order_number']);  // 杨静秋
        $manage_mobile = $part_order_number['value'];

        $address = $order_data['province'] . $order_data['city'] . $order_data['area'] . $order_data['address'];

        /* +  -----    订单生成成功，发送短信通知  ----- + */
        if (Request::domain() != 'http://localhost:8068') {
            $param = [
                'mobile' => $manage_mobile,
                'type' => 2,
                'order_sn' => $order_data['order_sn'],
                'address' => $address,
                'linkman' => $order_data['consignee'],
                'address_mobile' => $order_data['mobile']
            ];
            NoteCodeService::send_code($param);
        }

        /* +  -----    订单生成成功，发送微信模板消息通知  ----- + */
        $member = MemberModel::get(['username' => $manage_mobile]);
        if ($member && $member['openid']) {
            $param = [
                'touser' => $member['openid'],
                'template_id' => '-wjkS0vN_NOaiYY6biMRlySepDiPxzUu3TfcFb5FQnk',
                'url' => '',
                'data' => [
                    'first' => [ 'value' => '发现'.$type.'订单', 'color' => '#173177'],
                    'keyword1' => [ 'value' => $order_data['order_sn'], 'color' => '#173177'],
                    'keyword2' => [ 'value' => date('Y-m-d H:i:s'), 'color' => '#173177'],
                    'remark' => [ 'value' => "请尽快处理 \n 联系人：" . $order_data['consignee'] . " \n 联系电话：" . $order_data['mobile'] . " \n 收货地址：" . $address, 'color' => '#173177'],
                ]
            ];
            send_wechat_tmplmsg(json_encode($param));
        }
    }

    /**
     * 获取物流信息
     * @param $order
     * @param $express_sn
     * @param $product
     * @return array
     * @throws OrderException
     */
    public static function expressInfo($order, $express_sn, $product) {
        if (!$order) {
            throw new OrderException();
        }

        if ($order->express_subscription == 0) {
            ExpressService::subscriptionExpress($order, $express_sn);
        }

        // 获取物流信息
        $express = ExpressModel::get(['express_sn' => $express_sn]);

        $data = [
            'status' => $express ? $express->status : 0,
            'company' => $express ? $express->company : '',
            'context' => $express ? json_decode($express->context, true) : '',
            'order_sn' => $order->order_sn,
            'express_sn' => $order->express_sn,
            'thumb' => $order->$product->thumb
        ];

        return $data;
    }

    /**
     * 根据状态获取订单数量
     * @param $uid
     * @return array
     */
    public static function getOrderNum($uid) {
        // 定制订单数据
        $dfk = OrderModel::getMemberOrderCount($uid, 1);
        $ltsyjd = OrderModel::getMemberOrderCount($uid, 3);
        $yfh = OrderModel::getMemberOrderCount($uid, 5);
        $dpj = OrderModel::getMemberOrderCount($uid, 6);


        // 销售订单数据
        $xs_dfk = OrderBuyModel::getMemberOrderBuyCount($uid, 1);
        $xs_dfh = OrderBuyModel::getMemberOrderBuyCount($uid, 2);
        $xs_yfh = OrderBuyModel::getMemberOrderBuyCount($uid, 3);
        $xs_dpj = OrderBuyModel::getMemberOrderBuyCount($uid, 6);

        return [
            'dfk' => $dfk,
            'ltsyjd' => $ltsyjd,
            'yfh' => $yfh,
            'dpj' => $dpj,
            'xs_dfk' => $xs_dfk,
            'xs_dfh' => $xs_dfh,
            'xs_yfh' => $xs_yfh,
            'xs_dpj' => $xs_dpj,
        ];
    }

    /**
     * 充值订单结算
     * @param $order_id
     * @return array
     */
    public static function sub_order_recharge_account($order_id) {
        try {
            // 获取配置信息
            $system = config('system');

            /* + --------------  订单信息  -------------------+ */
            $order = model('order_recharge')->get(['id' => $order_id]);
            if (!$order) {
                throw new \Exception('订单不存在');
            }

            if ($order->sub_account_status != 0) {
                throw new \Exception('已分账');
            }

            model('order_recharge')->save(['sub_account_status' => 1], ['id' => $order_id]);

            /* + --------------  待结算金额  -------------------+ */
            $for_the_account_price = $order->money;

            //throw new \Exception('这里没有问题');

            /* + --------------  用户信息  -------------------+ */
            $member = $order->orderMember;
            // 用户充值业绩在充值成功的时候已经添加  pay.php

            /* + --------------  推荐人收益  -------------------+ */
            $parent_id = $member->parent_id;
            if ($parent_id > 0) {
                //  用户直推获得订单单价的15%做为余额收益
                //  条件是必须有任一正常身份或者有购买订单
                $p_order = model('order')->get(['member_id' => $parent_id, 'status' => ['gt', 1]]);
                $p_order_buy = model('order_buy')->get(['member_id' => $parent_id, 'status' => 7]);
                $zt_parent = model('member')->get(['id' => $parent_id]);
                if (($zt_parent->memberCouncilor && $zt_parent->memberCouncilor->status == 1)
                    || ($zt_parent->memberShop && $zt_parent->memberShop->status == 2)
                    || ($zt_parent->memberPartner && $zt_parent->memberPartner->status == 1)
                    || ($zt_parent->memberPatternMaster && $zt_parent->memberPatternMaster->status == 2) || $p_order || $p_order_buy) {
                    $recommended_income = $for_the_account_price * $system['role_direct_drive'];
                    model('member')->where(['id' => $parent_id])->setInc('money', $recommended_income);
                    MemberBill::add_member_bill($parent_id, $recommended_income, '直推奖励', 3, $order->order_sn, 'order_recharge', '系统分配');
                }
            }

            if ($member->parents) {
                /* + --------------  业绩 -- 所有上级团队全部累积业绩  -------------------+ */
                model('member')->where(['id' => ['in', $member->parents]])->setInc('performance', $order->money);
                self::add_performance_log($member->parents, $order->order_sn, $order->money);

                /* + --------------  整理用户上级团队  -------------------+ */
                $f_list = explode(',', $member->parents);
                rsort($f_list);  // 根据值倒排

                // 定义合伙人业绩档位和对应的分成比例
                $performance_gears = [
                    ['performance' => $system['partner_level_four_performance'], 'divide_into' => $system['partner_level_four_earnings']],
                    ['performance' => $system['partner_level_three_performance'], 'divide_into' => $system['partner_level_three_earnings']],
                    ['performance' => $system['partner_level_two_performance'], 'divide_into' => $system['partner_level_two_earnings']],
                    ['performance' => $system['partner_level_one_performance'], 'divide_into' => $system['partner_level_one_earnings']]
                ];

                // 合伙人收益上限
                $divide_into = $system['partner_level_four_earnings'];

                // 初始化合伙人已分配的档位
                $location_performance_gears = ['performance' => 0, 'divide_into' => 0];

                $councilor_earnings = 0; // 标识店铺收益是否已经分出
                $shop_earnings = 0; // 标识店铺收益是否已经分出
                $partner_divide_into = 0; // 初始化合伙人以分成比例

                // 循环团队用户
                //throw new \Exception('推荐人' . json_encode($f_list));
                foreach ($f_list as $member_id) {
                    $parent = model('member')->get(['id' => $member_id]);
                    if (!($parent->memberCouncilor && $parent->memberCouncilor->status == 1)
                        && !($parent->memberShop && $parent->memberShop->status == 2)
                        && !($parent->memberPartner && $parent->memberPartner->status == 1))
                    {
                        // 如果该用户不具备合伙人、门店、督导中的任一身份或者状态不是已审核，跳过循环
                        continue;
                    }
                    //throw new \Exception('开始循环');
                    /* + --------------  门店 -- 上级团队中第一个门店获得门店收益  -------------------+ */
                    if ($shop_earnings == 0 && $parent->memberShop && $parent->memberShop->status == 2 && $councilor_earnings == 0) {
                        $recommended_income = $for_the_account_price * $system['shop_order_earnings'];
                        model('member')->where(['id' => $member_id])->setInc('money', $recommended_income);
                        MemberBill::add_member_bill($member_id, $recommended_income, '充值订单门店收益', 3, $order->order_sn, 'order_recharge',  '系统分配');
                        $shop_earnings++;
                    }

                    /* + -----
                        --   督导收益
                        ----  1. 检查前面是否存在店铺 ， 如果没有则获得店铺对应的收益比例
                        ----  2 督导和合伙人共享合伙人收益  不重复  -----------
                    ------
                    --+ */
                    if ($parent->memberCouncilor && $parent->memberCouncilor->status == 1) {
                        if($shop_earnings == 0 && $councilor_earnings == 0) {
                            $recommended_income = $for_the_account_price * $system['shop_order_earnings'];
                            model('member')->where(['id' => $member_id])->setInc('money', $recommended_income);
                            MemberBill::add_member_bill($member_id, $recommended_income, '充值订单督导门店收益', 3, $order->order_sn, 'order_recharge',  '系统分配');
                            $councilor_earnings++;
                        }
                        /* + --------------  督导和合伙人共享合伙人收益  不重复 -- 、、    -------------------+ */
                        foreach ($performance_gears as $v) {
                            //  用户业绩大于 定义的业绩  并且大于前面已经被分成的业绩  则给当前合伙人分配新的档位收益
                            if ($parent->performance >= $v['performance'] && $v['performance'] > $location_performance_gears['performance']) {
                                $earnings = $v['divide_into'] - $location_performance_gears['divide_into'];  //  当前合伙人实际分配的比例为   业绩所能分配比例减去之前的合伙人和督导已经分配的比例
                                $recommended_income = $for_the_account_price * $earnings;
                                model('member')->where(['id' => $member_id])->setInc('money', $recommended_income);
                                MemberBill::add_member_bill($member_id, $recommended_income, '充值订单督导合伙人收益', 3, $order->order_sn, 'order_recharge',  '系统分配');

                                //$partner_divide_into += $v['divide_into'];  // 累积合伙人以分成比例
                                $location_performance_gears = $v; // 记录当前分配比例   防止重复分配
                                // 分配完成  跳出循环
                                break;
                            }
                        }
                    }

                    /* + --------------  合伙人 -- 上级团队中合伙人按级别向上享受合伙人收益，分完即止，督导和合伙人收益共享，所以此处要检查之前是否有督导分走相关收益    -------------------+ */
                    foreach ($performance_gears as $v) {
                        //  用户业绩大于 定义的业绩  并且大于前面已经被分成的业绩  则给当前合伙人分配新的档位收益
                        if ($parent->performance >= $v['performance']
                            && $v['performance'] > $location_performance_gears['performance'])
                        {
                            $earnings = $v['divide_into'] - $location_performance_gears['divide_into'];  //  当前合伙人实际分配的比例为   业绩所能分配比例减去之前的合伙人和督导已经分配的比例
                            $recommended_income = $for_the_account_price * $earnings;
                            model('member')->where(['id' => $member_id])->setInc('money', $recommended_income);
                            MemberBill::add_member_bill($member_id, $recommended_income, '充值订单合伙人收益', 3, $order->order_sn, 'order_recharge',  '系统分配');

                            //$partner_divide_into += $v['divide_into'];  // 累积合伙人以分成比例
                            $location_performance_gears = $v; // 记录当前分配比例   防止重复分配
                            // 分配完成  跳出循环
                            break;
                        }
                    }

                    // 已分完最高档位，终止循环
                    if($location_performance_gears['performance'] == $system['partner_level_four_performance']) {
                        break;
                    }
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 添加业绩日志
     * @param $parents
     * @param $order_sn
     * @param $pay_price
     */
    public static function add_performance_log($parents, $order_sn, $pay_price) {
        $parents_array = explode(',', $parents);
        $performances = [];
        foreach ($parents_array as $v) {
            $performances[] = [
                'member_id' => $v,
                'order_sn' => $order_sn,
                'performance' => $pay_price
            ];
        }
        model('performance')->saveAll($performances);
    }
}